package com.midongtech.cpd.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.midongtech.cpd.R;
import com.midongtech.cpd.TaskActivity;
import com.midongtech.cpd.TaskRefresh;
import com.midongtech.cpd.bean.AppData;
import com.midongtech.cpd.constants.MonitorConstant;
import com.midongtech.cpd.AppDownloadListener;
import com.midongtech.cpd.utils.AppUtils;
import com.midongtech.cpd.utils.DownLoadApkManager;
import com.midongtech.cpd.utils.HttpManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



public class AdListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements AppDownloadListener {

    private static final String TAG = "AdListAdapter";
    private List<AppData> mList = new ArrayList<>();
    private Activity mContext;
    TaskRefresh mTaskRefresh;
    private DownLoadApkManager mDownLoadApkManager;
    private AppData mCurrentTask;
    private final int INTERVAL = 3;

    //app体验监听
    public  Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            mHandler.sendEmptyMessageDelayed(0x01,INTERVAL * 1000);
            if (mCurrentTask != null) {
                String[] appInfo = AppUtils.getTopAppInfo(mContext);
                Log.i(TAG,"当前栈顶包名："+appInfo[0] + "   任务包名："+mCurrentTask.getPkg());
                if (appInfo[0].equals(mCurrentTask.getPkg())) { //栈顶包名跟当前做的任务匹配
                    if(mCurrentTask.getDoingTime()==0) {
                        HttpManager.monitor(mContext, mCurrentTask, MonitorConstant.APP_OPEN, null);
                    }
                    Log.i(TAG,"任务体验中，累计体验时长："+mCurrentTask.getDoingTime() + "   需体验时长："+mCurrentTask.getDuration());
                    mCurrentTask.setDoingTime(mCurrentTask.getDoingTime()+INTERVAL);
                    if (mCurrentTask.getDoingTime() >= mCurrentTask.getDuration()) { //任务完成
                        Log.i(TAG,mCurrentTask.getName() + "  任务已完成");
                        HttpManager.monitor(mContext, mCurrentTask, MonitorConstant.TASK_FINISH, null);
                        Toast.makeText(mContext,"任务已完成",Toast.LENGTH_LONG).show();
                        cancelMonitor();
                        //任务完成后，记得刷新任务列表
                        mTaskRefresh.onrefresh();
                    }
                }

            }
        }
    };

    private void startMonitor() {
        mHandler.removeCallbacksAndMessages(null);
        mHandler.sendEmptyMessageDelayed(0x01,0);
    }

    private void cancelMonitor() {
        mHandler.removeCallbacksAndMessages(null);
    }

    public AdListAdapter(Activity context, List<AppData> list, TaskRefresh taskRefresh) {
        this.mContext = context;
        mTaskRefresh = taskRefresh;
        mDownLoadApkManager = DownLoadApkManager.getInstance(mContext, this);
        if (list != null) {
            mList.addAll(list);
        }

    }


    public void setData(List<AppData> list) {
        mList.clear();
        if (list != null) {
            mList.addAll(list);
        }
        notifyDataSetChanged();
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.ad_list_item, parent, false);
        return new AppViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        final AppViewHolder appViewHolder = (AppViewHolder) holder;
        if (mList != null && mList.size() > 0) {
            final AppData data = mList.get(position);
            if (data != null) {
                HttpManager.monitor(mContext, data, MonitorConstant.APP_DISPLAY, null);
                if (!mViewHolderList.containsKey(data.getApkid())) {
                    mViewHolderList.put(data.getApkid() + "", appViewHolder);
                }

                appViewHolder.mTitleTv.setText(data.getName());
                appViewHolder.mDesTv.setText( data.getDescription());
                Glide.with(mContext).load(data.getLogo()).into(appViewHolder.mIconIv);

                appViewHolder.mSizeIv.setText(data.getSize() + "M");
                if (AppUtils.isAppInstalled(mContext, data.getPkg())) {
                    appViewHolder.mDownloadTv.setText("继续体验");
                    appViewHolder.progressBar.setProgress(100);
                } else {
                    appViewHolder.mDownloadTv.setText("立即下载");
                }



                appViewHolder.mDownloadTv.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        mCurrentTask = data;
                        startMonitor();
                        if (AppUtils.isAppInstalled(mContext,data.getPkg())) {
                            AppUtils.startApp(mContext,data.getPkg());
                        } else {
                            mDownLoadApkManager.startDownload(data.getDownload_link(),data.getName(),data.getPkg(),data.getApkid()+"");
                        }

                    }
                });
            }
        }
    }

    private Map<String, AppViewHolder> mViewHolderList = new HashMap<>();

    @Override
    public int getItemCount() {
        return mList.size();
    }

    @Override
    public void onDownloadStart(String appId, String packageName) {
        Log.i(TAG,"onDownloadStart appId:"+appId+"   packageName:"+packageName);
        HttpManager.monitor(mContext, TaskActivity.getAppDataByPkg(packageName), MonitorConstant.DOWNLOAD_START, null);
    }

    @Override
    public void onDownloadFail(String appId, String packageName) {
        Log.i(TAG,"onDownloadFail appId:"+appId+"   packageName:"+packageName);
    }

    @Override
    public void onDownloadSuccess(String appId, String packageName) {
        Log.i(TAG,"onDownloadSuccess appId:"+appId+"   packageName:"+packageName);
        HttpManager.monitor(mContext, TaskActivity.getAppDataByPkg(packageName), MonitorConstant.DOWNLOAD_FINISH, null);
        HttpManager.monitor(mContext, TaskActivity.getAppDataByPkg(packageName), MonitorConstant.INSTALL_START, null);
    }

    @Override
    public void onProgressUpdate(String appId, String packageName, int progress) {
        Log.i(TAG,"onProgressUpdate appId:"+appId+"   packageName:"+packageName+"  progress:"+progress);
        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                final AppViewHolder appViewHolder = mViewHolderList.get(appId);
                appViewHolder.progressBar.setProgress(progress);
                if (progress >= 100) {
                    appViewHolder.mDownloadTv.setText("安装打开");
                }
            }
        });
    }


    class AppViewHolder extends RecyclerView.ViewHolder {

        View view;
        TextView mTitleTv;
        TextView mDesTv;
        ImageView mIconIv;
        TextView mSizeIv;
        TextView mRewardTv;
        TextView mDownloadTv;
        ProgressBar progressBar;

        public AppViewHolder(View itemView) {
            super(itemView);
            view = itemView;

            mTitleTv = itemView.findViewById(R.id.tv_title);//标题
            mDesTv = itemView.findViewById(R.id.tv_des);//标题
            mRewardTv = itemView.findViewById(R.id.tv_reward);//标题
            mSizeIv = itemView.findViewById(R.id.tv_size);//标题
            mDownloadTv = itemView.findViewById(R.id.tv_download);//标题
            mIconIv = itemView.findViewById(R.id.iv_icon);//标题
            progressBar = itemView.findViewById(R.id.progress);//标题

        }
    }


}